import { useContext, useEffect, useState } from 'react';
import {BrowserRouter as Router, Switch, Route, Redirect, useHistory} from 'react-router-dom';

import './App.css';

import {ConnContext, ConnProvider} from './Page/contexts/Conn';

import Login from './Page/Login';
import Register from './Page/Register';
import Deck from './Page/Deck';
import { BookProvider } from './Page/contexts/Book';

const SecuredRoute = ({path, comp: Comp, ...restArgs}) => {

  const {cred} = useContext(ConnContext);

  const render = () => {
    if (path === '/log') {
      if (cred?.role === 'USER') {
        return <Comp {...restArgs} />
      } else {
        return <Login />
      }
    } else {
      if (cred?.role !== 'USER'){
        return <Login />
      } else {
        return <Comp {...restArgs} />
      }
    }
  }

  return <Route path={path} render={render} />
}

function App() {

  const history = useHistory();

  return (
    <div className="App">
      {/* <ConnProvider {...{url: 'http://localhost:3000'}}> */}
        <BookProvider>
          <Router {...{history}}>
            <Switch>
              <Route path='/reg' render={() => <Register />} exact />
              <SecuredRoute path="/" comp={Deck} />
            </Switch>
          </Router>
        </BookProvider>
      {/* </ConnProvider> */}

    </div>
  );
}

export default App;
